package com.leetcode.a001;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zhengqn
 * @Title: Solution
 * @Description: 两数相加
 * @date 2019/12/18 11:00
 */
public class TwoSum {

    /**
     * 暴力破解法
     * 要求 1、数组中元素不重复使用
     * 2、假设只有一个答案
     * 使用嵌套for循环来求解
     */
    public int[] twoSum(int[] nums, int target){
        if(nums == null || nums.length < 1){
            throw new IllegalArgumentException("参数不合法");
        }
        for (int i = 0; i < nums.length-1; i++) {
            for (int j = i+1; j < nums.length; j++) {
                if(nums[i] + nums[j] == target){
                    return new int[]{i,j};
                }

            }
        }
        throw new IllegalArgumentException("无符合结果");
    }

    public int[] twoSum1(int[] nums, int target){
        Map<Integer, Integer> map = new HashMap<>(nums.length);
        for (int i = 0; i < nums.length; i++) {
            int temp = target - nums[i];
            if (map.containsKey(temp)) {
                int j = map.get(temp);
                return new int[]{i, j};
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("无符合结果");
    }

    public static void main(String[] args) {
        TwoSum solution = new TwoSum();
        System.out.println(Arrays.toString(solution.twoSum1(new int[]{2, 7, 11, 15}, 26)));
    }
}
